import React, { useEffect, useRef, useState } from 'react';
import {
  Button,
  Radio,
  Form,
  Row,
  Col,
  Select,
  Input,
  message,
  Divider,
  Descriptions,
  Modal,
} from 'antd';
import request from '@/utils/request';
import { connect } from 'dva';
import ComboGrid from '@/components/ComboGrid';

const isEmptyObj = obj => {
  if (obj === undefined || Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

const isEmptyStr = str => {
  if (str === undefined || str === null || str === '') {
    return true;
  }
  return false;
};

function Operpage(props) {
  const { getFieldDecorator } = props.form;
  const [loading, setLoading] = useState(false);
  const [orderFromMap, setOrderFrom] = useState([]);
  const [exceptionTypeMap, setExceptionType] = useState([]);
  const [solveTypeMap, setSolveType] = useState([]);
  const [isShowSolveType, setIsShowSolveType] = useState(true);
  const [isShowRetryNum, setIsShowRetryNum] = useState(true);

  const showOrHiddenBySolveType = solveType => {
    if (solveType === '0') {
      setIsShowSolveType(true);
    } else {
      setIsShowSolveType(false);
      if (solveType === '2') {
        setIsShowRetryNum(false);
      } else {
        setIsShowRetryNum(true);
      }
    }
  };

  useEffect(() => {
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'OrderExceptionModel',
        attrNbr: 'orderFrom',
      },
    }).then(res => {
      setOrderFrom(res);
    });
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'OrderExceptionModel',
        attrNbr: 'exceptionType',
      },
    }).then(res => {
      setExceptionType(res);
    });
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'OrderExceptionModel',
        attrNbr: 'solveType',
      },
    }).then(res => {
      setSolveType(res);
    });
    if (!isEmptyObj(props.passData)) {
      showOrHiddenBySolveType(props.passData.solveType.toString());
    }
  }, []);

  const handleSubmit = () => {
    props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.solveType === '1') {
        if (isEmptyObj(fieldsValue.planName)) {
          Modal.warning({ content: '请选择解决方案' });
          return;
        }
      } else if (fieldsValue.solveType === '2') {
        if (isEmptyStr(fieldsValue.retryNum)) {
          Modal.warning({ content: '请输入重试次数' });
          return;
        }
        if (!/[0-9]/.test(fieldsValue.retryNum)) {
          Modal.warning({ content: '重试次数请输入数字' });
          return;
        }
        if (isEmptyObj(fieldsValue.planName)) {
          Modal.warning({ content: '请选择解决方案' });
          return;
        }
      }
      const paramsObj = {
        planId: fieldsValue.planName[0].planId,
        planName: fieldsValue.planName[0].planName,
        ...fieldsValue,
        exeptionModelId: props.passData.exeptionModelId,
      };
      setLoading(true);
      request('pmc/pms/ExceptionOrdController/update', {
        data: paramsObj,
        method: 'POST',
      }).then(res => {
        if (res) {
          props.close(), props.refresh(), setLoading(false), message.success('保存成功！');
        } else {
          message.error('保存失败！'), setLoading(false);
        }
      });
    });
  };

  const handleCreate = () => {
    props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.solveType === '1') {
        if (isEmptyObj(fieldsValue.planName)) {
          Modal.warning({ content: '请选择解决方案' });
          return;
        }

      } else if (fieldsValue.solveType === '2') {
        if (isEmptyStr(fieldsValue.retryNum)) {
          Modal.warning({ content: '请输入重试次数' });
          return;
        }
        if (!/[0-9]/.test(fieldsValue.retryNum)) {
          Modal.warning({ content: '重试次数请输入数字' });
          return;
        }
        if (isEmptyObj(fieldsValue.planName)) {
          Modal.warning({ content: '请选择解决方案' });
          return;
        }
      }
      const paramsObj = {
        ...fieldsValue,
      };
      if(fieldsValue.solveType === '1' || fieldsValue.solveType === '2'){
        paramsObj.planId = fieldsValue.planName[0].planId;
        paramsObj.planName = fieldsValue.planName[0].planName;
      }
      // console.log(fieldsValue)
      setLoading(true);
      request('pmc/pms/ExceptionOrdController/add', {
        data: paramsObj,
      }).then(res => {
        if (res) {
          props.close(), props.refresh(), setLoading(false);
          message.success('创建成功！');
        } else {
          message.error('创建失败！');
          setLoading(false);
        }
      });
    });
  };

  const onChangeSolveType = e => {
    showOrHiddenBySolveType(e.target.value);
  };

  return (
    <>
      <Form layout="vertical" onSubmit={handleSubmit}>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label="系统来源">
              {getFieldDecorator('orderFrom', {
                rules: [
                  {
                    required: true,
                    message: '系统来源不能为空',
                  },
                ],
              })(
                <Select allowClear placeholder="请选择">
                  {orderFromMap.map(item => {
                    return (
                      <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                    );
                  })}
                </Select>
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="异常分类">
              {getFieldDecorator('exceptionType', {
                rules: [
                  {
                    required: true,
                    message: '异常分类不能为空',
                  },
                ],
              })(
                <Select allowClear placeholder="请选择">
                  {exceptionTypeMap.map(item => {
                    return (
                      <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                    );
                  })}
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label="异常名称">
              {getFieldDecorator('exceptionModelName', {
                rules: [
                  {
                    required: true,
                    message: '异常名称不能为空',
                  },
                ],
              })(<Input allowClear placeholder="请输入" disabled={props.disabled} />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="异常编码">
              {getFieldDecorator('exceptionCode', {
                rules: [
                  {
                    required: true,
                    message: '异常编码不能为空',
                  },
                ],
              })(<Input allowClear placeholder="请输入" disabled={props.disabled} />)}
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label="解决方案类型">
              {getFieldDecorator('solveType', {
                rules: [
                  {
                    required: true,
                    message: '解决方案类型不能为空',
                  },
                ],
              })(
                <Radio.Group onChange={onChangeSolveType}>
                  {solveTypeMap.map(item => {
                    return <Radio value={item.attrValue}>{item.attrValueName}</Radio>;
                  })}
                </Radio.Group>
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="异常关键字">
              {getFieldDecorator('exceptionKey', {
                rules: [
                  {
                    required: true,
                    message: '异常关键字不能为空',
                  },
                ],
              })(<Input allowClear placeholder="请输入" disabled={props.disabled} />)}
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16} hidden={isShowSolveType}>
          <Col span={24}>
            <Row gutter={16} hidden={isShowRetryNum}>
              <Col span={24}>
                <Form.Item label="重试次数">
                  {getFieldDecorator('retryNum')(
                    <Input allowClear placeholder="请输入" disabled={props.disabled} />
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item label="解决方案">
                  {getFieldDecorator('planName')(
                    <ComboGrid
                      url="pmc/pms/RuleCfgController/findPlanPageQry"
                      popupStyle={{ width: 500 }}
                      placeholder="请选择关联方案"
                      searchPlaceholder="请输入方案名称进行搜索"
                      label="planName"
                      rowKey="planId"
                      pick="radio"
                      columns={[
                        {
                          title: '方案名称',
                          dataIndex: 'planName',
                        },
                        {
                          title: '方案编码',
                          dataIndex: 'planCode',
                          ellipsis: true,
                        },
                      ]}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item label="异常原因">
              {getFieldDecorator('exceptionReason', {
                rules: [
                  {
                    required: true,
                    message: '异常原因不能为空',
                  },
                ],
              })(<Input.TextArea rows={3} placeholder="请输入" disabled={props.disabled} />)}
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item label="异常提示语">
              {getFieldDecorator('exceptionTips', {
                rules: [
                  {
                    required: true,
                    message: '异常提示语不能为空',
                  },
                ],
              })(<Input.TextArea rows={3} placeholder="请输入" disabled={props.disabled} />)}
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div
        style={{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }}
      >
        {props.status === 'add' ? (
          <Button type="primary" className="margin-right" onClick={handleCreate} loading={loading}>
            创建
          </Button>
        ) : props.status === 'edit' ? (
          <Button type="primary" className="margin-right" onClick={handleSubmit} loading={loading}>
            保存
          </Button>
        ) : null}
        <Button type="ghost" className="margin-left" onClick={props.close}>
          取消
        </Button>
      </div>
    </>
  );
}

// export default Form.create(
//
// )(Operpage);

export default connect(({ abnormalConfig }) => ({
  passData: abnormalConfig.passData,
}))(
  Form.create({
    mapPropsToFields(props) {
      if (!isEmptyObj(props.passData)) {
        return {
          orderFrom: Form.createFormField({ value: props.passData.orderFrom }),
          exceptionModelName: Form.createFormField({ value: props.passData.exceptionModelName }),
          exceptionCode: Form.createFormField({ value: props.passData.exceptionCode }),
          exceptionType: Form.createFormField({ value: props.passData.exceptionType.toString() }),
          exceptionKey: Form.createFormField({ value: props.passData.exceptionKey }),
          exceptionReason: Form.createFormField({ value: props.passData.exceptionReason }),
          exceptionTips: Form.createFormField({ value: props.passData.exceptionTips }),
          solveType: Form.createFormField({ value: props.passData.solveType.toString() }),
          retryNum: Form.createFormField({ value: props.passData.retryNum }),
          planName: Form.createFormField({
            value: props.passData.planList ? props.passData.planList : [],
          }),
        };
      }
    },
  })(Operpage)
);
